import React, { useState, useEffect, useRef } from 'react';
import {
  Drawer, List, Badge, Button, Space, Typography, Tabs, Empty, Spin,
  Dropdown, Modal, message, Tag, Avatar, Tooltip, Input, Select,
  DatePicker, Card, Row, Col, Statistic, Divider, Popconfirm
} from 'antd';
import {
  BellOutlined, SettingOutlined, DeleteOutlined, EyeOutlined,
  InboxOutlined, ReloadOutlined, FilterOutlined, ExportOutlined,
  CheckOutlined, CloseOutlined, InfoCircleOutlined, ExclamationCircleOutlined,
  CheckCircleOutlined, CloseCircleOutlined, WarningOutlined
} from '@ant-design/icons';
import type { TabsProps } from 'antd';
import {
  notificationService,
  NotificationItem,
  NotificationStats,
  NotificationSearchParams
} from '@/services/notificationService';

const { Text, Title } = Typography;
const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;

interface NotificationCenterProps {
  visible: boolean;
  onClose: () => void;
  onUnreadCountChange?: (count: number) => void;
}

interface NotificationState {
  notifications: NotificationItem[];
  loading: boolean;
  stats: NotificationStats | null;
  selectedTab: string;
  selectedNotifications: string[];
  searchParams: NotificationSearchParams;
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
}

export default function NotificationCenter({
  visible,
  onClose,
  onUnreadCountChange
}: NotificationCenterProps) {
  const [state, setState] = useState<NotificationState>({
    notifications: [],
    loading: false,
    stats: null,
    selectedTab: 'all',
    selectedNotifications: [],
    searchParams: {},
    pagination: {
      current: 1,
      pageSize: 20,
      total: 0
    }
  });

  const [showFilters, setShowFilters] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedNotification, setSelectedNotification] = useState<NotificationItem | null>(null);
  const wsRef = useRef<WebSocket | null>(null);

  // 加载通知列表
  const loadNotifications = async (params?: Partial<NotificationSearchParams>) => {
    setState(prev => ({ ...prev, loading: true }));
    
    try {
      const searchParams = {
        ...state.searchParams,
        ...params,
        page: state.pagination.current - 1,
        size: state.pagination.pageSize
      };

      // 根据选中的标签页设置状态过滤
      if (state.selectedTab === 'unread') {
        searchParams.status = 'unread';
      } else if (state.selectedTab === 'read') {
        searchParams.status = 'read';
      } else if (state.selectedTab === 'archived') {
        searchParams.status = 'archived';
      }

      const response = await notificationService.getNotifications(searchParams);
      
      setState(prev => ({
        ...prev,
        notifications: response.content,
        pagination: {
          ...prev.pagination,
          total: response.totalElements
        },
        loading: false
      }));
    } catch (error: any) {
      console.error('加载通知失败:', error);
      message.error('加载通知失败');
      setState(prev => ({ ...prev, loading: false }));
    }
  };

  // 加载统计数据
  const loadStats = async () => {
    try {
      const stats = await notificationService.getNotificationStats();
      setState(prev => ({ ...prev, stats }));
      
      if (onUnreadCountChange) {
        onUnreadCountChange(stats.unread);
      }
    } catch (error: any) {
      console.error('加载统计数据失败:', error);
    }
  };

  // 初始化WebSocket连接
  const initWebSocket = async () => {
    try {
      const ws = await notificationService.connectWebSocket();
      wsRef.current = ws;
      
      ws.onmessage = (event) => {
        const notification = JSON.parse(event.data) as NotificationItem;
        
        // 添加新通知到列表
        setState(prev => ({
          ...prev,
          notifications: [notification, ...prev.notifications]
        }));
        
        // 更新统计数据
        loadStats();
        
        // 显示浏览器通知
        if (Notification.permission === 'granted') {
          new Notification(notification.title, {
            body: notification.content,
            icon: '/favicon.svg'
          });
        }
      };
    } catch (error: any) {
      console.error('WebSocket连接失败:', error);
    }
  };

  // 组件初始化
  useEffect(() => {
    if (visible) {
      loadNotifications();
      loadStats();
      initWebSocket();
      
      // 请求浏览器通知权限
      if (Notification.permission === 'default') {
        Notification.requestPermission();
      }
    }
    
    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, [visible]);

  // 标签页变化时重新加载
  useEffect(() => {
    if (visible) {
      loadNotifications();
    }
  }, [state.selectedTab]);

  // 获取通知类型图标
  const getNotificationIcon = (type: NotificationItem['type']) => {
    const iconProps = { style: { fontSize: 16 } };
    
    switch (type) {
      case 'success':
        return <CheckCircleOutlined {...iconProps} style={{ ...iconProps.style, color: '#52c41a' }} />;
      case 'warning':
        return <WarningOutlined {...iconProps} style={{ ...iconProps.style, color: '#faad14' }} />;
      case 'error':
        return <CloseCircleOutlined {...iconProps} style={{ ...iconProps.style, color: '#ff4d4f' }} />;
      case 'info':
        return <InfoCircleOutlined {...iconProps} style={{ ...iconProps.style, color: '#1890ff' }} />;
      case 'system':
        return <BellOutlined {...iconProps} style={{ ...iconProps.style, color: '#722ed1' }} />;
      default:
        return <BellOutlined {...iconProps} />;
    }
  };

  // 获取优先级颜色
  const getPriorityColor = (priority: NotificationItem['priority']) => {
    switch (priority) {
      case 'urgent': return 'red';
      case 'high': return 'orange';
      case 'medium': return 'blue';
      case 'low': return 'default';
      default: return 'default';
    }
  };

  // 处理通知操作
  const handleNotificationAction = async (action: string, notification?: NotificationItem) => {
    try {
      switch (action) {
        case 'read':
          if (notification) {
            await notificationService.markAsRead(notification.id);
            message.success('已标记为已读');
          }
          break;
        case 'archive':
          if (notification) {
            await notificationService.archiveNotification(notification.id);
            message.success('已归档');
          }
          break;
        case 'delete':
          if (notification) {
            await notificationService.deleteNotification(notification.id);
            message.success('已删除');
          }
          break;
        case 'batch_read':
          if (state.selectedNotifications.length > 0) {
            await notificationService.markBatchAsRead(state.selectedNotifications);
            message.success('批量标记已读成功');
            setState(prev => ({ ...prev, selectedNotifications: [] }));
          }
          break;
        case 'batch_archive':
          if (state.selectedNotifications.length > 0) {
            await notificationService.archiveBatchNotifications(state.selectedNotifications);
            message.success('批量归档成功');
            setState(prev => ({ ...prev, selectedNotifications: [] }));
          }
          break;
        case 'batch_delete':
          if (state.selectedNotifications.length > 0) {
            await notificationService.deleteBatchNotifications(state.selectedNotifications);
            message.success('批量删除成功');
            setState(prev => ({ ...prev, selectedNotifications: [] }));
          }
          break;
        case 'mark_all_read':
          await notificationService.markAllAsRead();
          message.success('全部标记已读成功');
          break;
        default:
          break;
      }
      
      // 重新加载数据
      loadNotifications();
      loadStats();
    } catch (error: any) {
      console.error(`${action}操作失败:`, error);
      message.error(`${action}操作失败`);
    }
  };

  // 查看通知详情
  const viewNotificationDetail = (notification: NotificationItem) => {
    setSelectedNotification(notification);
    setDetailModalVisible(true);
    
    // 如果是未读通知，标记为已读
    if (notification.status === 'unread') {
      handleNotificationAction('read', notification);
    }
  };

  // 搜索和筛选
  const handleSearch = (params: Partial<NotificationSearchParams>) => {
    setState(prev => ({
      ...prev,
      searchParams: { ...prev.searchParams, ...params },
      pagination: { ...prev.pagination, current: 1 }
    }));
    loadNotifications(params);
  };

  // 导出通知
  const handleExport = async () => {
    try {
      const blob = await notificationService.exportNotifications({
        format: 'excel',
        ...state.searchParams
      });
      
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `notifications-${new Date().toISOString().split('T')[0]}.xlsx`;
      link.click();
      window.URL.revokeObjectURL(url);
      
      message.success('导出成功');
    } catch (error: any) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };

  // 标签页配置
  const tabItems: TabsProps['items'] = [
    {
      key: 'all',
      label: (
        <Space>
          <span>全部</span>
          {state.stats && <Badge count={state.stats.total} showZero />}
        </Space>
      )
    },
    {
      key: 'unread',
      label: (
        <Space>
          <span>未读</span>
          {state.stats && <Badge count={state.stats.unread} />}
        </Space>
      )
    },
    {
      key: 'read',
      label: (
        <Space>
          <span>已读</span>
          {state.stats && <Badge count={state.stats.read} showZero />}
        </Space>
      )
    },
    {
      key: 'archived',
      label: (
        <Space>
          <span>已归档</span>
          {state.stats && <Badge count={state.stats.archived} showZero />}
        </Space>
      )
    }
  ];

  return (
    <>
      <Drawer
        title={
          <Space>
            <BellOutlined />
            <span>通知中心</span>
            {state.stats && state.stats.unread > 0 && (
              <Badge count={state.stats.unread} />
            )}
          </Space>
        }
        placement="right"
        width={600}
        open={visible}
        onClose={onClose}
        extra={
          <Space>
            <Tooltip title="刷新">
              <Button 
                type="text" 
                icon={<ReloadOutlined />} 
                onClick={() => {
                  loadNotifications();
                  loadStats();
                }}
              />
            </Tooltip>
            <Tooltip title="筛选">
              <Button 
                type="text" 
                icon={<FilterOutlined />} 
                onClick={() => setShowFilters(!showFilters)}
              />
            </Tooltip>
            <Tooltip title="导出">
              <Button 
                type="text" 
                icon={<ExportOutlined />} 
                onClick={handleExport}
              />
            </Tooltip>
            <Tooltip title="设置">
              <Button 
                type="text" 
                icon={<SettingOutlined />} 
                onClick={() => message.info('通知设置功能开发中...')}
              />
            </Tooltip>
          </Space>
        }
      >
        {/* 统计信息 */}
        {state.stats && (
          <Card size="small" style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={6}>
                <Statistic title="总数" value={state.stats.total} />
              </Col>
              <Col span={6}>
                <Statistic title="未读" value={state.stats.unread} valueStyle={{ color: '#ff4d4f' }} />
              </Col>
              <Col span={6}>
                <Statistic title="已读" value={state.stats.read} valueStyle={{ color: '#52c41a' }} />
              </Col>
              <Col span={6}>
                <Statistic title="已归档" value={state.stats.archived} valueStyle={{ color: '#1890ff' }} />
              </Col>
            </Row>
          </Card>
        )}

        {/* 搜索和筛选 */}
        <Card size="small" style={{ marginBottom: 16 }}>
          <Space direction="vertical" style={{ width: '100%' }}>
            <Search
              placeholder="搜索通知..."
              allowClear
              onSearch={(value) => handleSearch({ keyword: value })}
            />
            
            {showFilters && (
              <Row gutter={[8, 8]}>
                <Col span={8}>
                  <Select
                    placeholder="类型"
                    allowClear
                    style={{ width: '100%' }}
                    onChange={(value) => handleSearch({ type: value })}
                  >
                    <Option value="info">信息</Option>
                    <Option value="success">成功</Option>
                    <Option value="warning">警告</Option>
                    <Option value="error">错误</Option>
                    <Option value="system">系统</Option>
                  </Select>
                </Col>
                <Col span={8}>
                  <Select
                    placeholder="优先级"
                    allowClear
                    style={{ width: '100%' }}
                    onChange={(value) => handleSearch({ priority: value })}
                  >
                    <Option value="urgent">紧急</Option>
                    <Option value="high">高</Option>
                    <Option value="medium">中</Option>
                    <Option value="low">低</Option>
                  </Select>
                </Col>
                <Col span={8}>
                  <RangePicker
                    placeholder={['开始日期', '结束日期']}
                    style={{ width: '100%' }}
                    onChange={(dates) => {
                      if (dates) {
                        handleSearch({
                          dateRange: {
                            start: dates[0]?.toISOString() || '',
                            end: dates[1]?.toISOString() || ''
                          }
                        });
                      }
                    }}
                  />
                </Col>
              </Row>
            )}
          </Space>
        </Card>

        {/* 批量操作 */}
        {state.selectedNotifications.length > 0 && (
          <Card size="small" style={{ marginBottom: 16 }}>
            <Space>
              <Text>已选择 {state.selectedNotifications.length} 项</Text>
              <Button size="small" onClick={() => handleNotificationAction('batch_read')}>
                标记已读
              </Button>
              <Button size="small" onClick={() => handleNotificationAction('batch_archive')}>
                批量归档
              </Button>
              <Popconfirm
                title="确定要删除选中的通知吗？"
                onConfirm={() => handleNotificationAction('batch_delete')}
              >
                <Button size="small" danger>
                  批量删除
                </Button>
              </Popconfirm>
            </Space>
          </Card>
        )}

        {/* 快捷操作 */}
        <Card size="small" style={{ marginBottom: 16 }}>
          <Space>
            <Button 
              size="small" 
              onClick={() => handleNotificationAction('mark_all_read')}
              disabled={!state.stats || state.stats.unread === 0}
            >
              全部标记已读
            </Button>
          </Space>
        </Card>

        {/* 通知列表 */}
        <Tabs
          activeKey={state.selectedTab}
          onChange={(key) => setState(prev => ({ ...prev, selectedTab: key }))}
          items={tabItems}
        />

        <Spin spinning={state.loading}>
          {state.notifications.length === 0 ? (
            <Empty description="暂无通知" />
          ) : (
            <List
              dataSource={state.notifications}
              renderItem={(notification) => (
                <List.Item
                  className={notification.status === 'unread' ? 'bg-blue-50' : ''}
                  actions={[
                    <Tooltip title="查看详情">
                      <Button 
                        type="text" 
                        size="small" 
                        icon={<EyeOutlined />}
                        onClick={() => viewNotificationDetail(notification)}
                      />
                    </Tooltip>,
                    notification.status === 'unread' && (
                      <Tooltip title="标记已读">
                        <Button 
                          type="text" 
                          size="small" 
                          icon={<CheckOutlined />}
                          onClick={() => handleNotificationAction('read', notification)}
                        />
                      </Tooltip>
                    ),
                    <Tooltip title="归档">
                      <Button 
                        type="text" 
                        size="small" 
                        icon={<InboxOutlined />}
                        onClick={() => handleNotificationAction('archive', notification)}
                      />
                    </Tooltip>,
                    <Popconfirm
                      title="确定要删除这条通知吗？"
                      onConfirm={() => handleNotificationAction('delete', notification)}
                    >
                      <Tooltip title="删除">
                        <Button 
                          type="text" 
                          size="small" 
                          icon={<DeleteOutlined />}
                          danger
                        />
                      </Tooltip>
                    </Popconfirm>
                  ].filter(Boolean)}
                >
                  <List.Item.Meta
                    avatar={
                      <div style={{ position: 'relative' }}>
                        {getNotificationIcon(notification.type)}
                        {notification.status === 'unread' && (
                          <div 
                            style={{
                              position: 'absolute',
                              top: -2,
                              right: -2,
                              width: 8,
                              height: 8,
                              backgroundColor: '#ff4d4f',
                              borderRadius: '50%'
                            }}
                          />
                        )}
                      </div>
                    }
                    title={
                      <Space>
                        <span 
                          className={notification.status === 'unread' ? 'font-semibold' : ''}
                          style={{ cursor: 'pointer' }}
                          onClick={() => viewNotificationDetail(notification)}
                        >
                          {notification.title}
                        </span>
                        <Tag color={getPriorityColor(notification.priority)}>
                          {notification.priority}
                        </Tag>
                        {notification.category && (
                          <Tag>{notification.category}</Tag>
                        )}
                      </Space>
                    }
                    description={
                      <div>
                        <div style={{ marginBottom: 4 }}>
                          {notification.content}
                        </div>
                        <Space size="small">
                          {notification.senderName && (
                            <Text type="secondary">来自: {notification.senderName}</Text>
                          )}
                          <Text type="secondary">
                            {new Date(notification.createdAt).toLocaleString()}
                          </Text>
                        </Space>
                      </div>
                    }
                  />
                </List.Item>
              )}
              pagination={{
                current: state.pagination.current,
                pageSize: state.pagination.pageSize,
                total: state.pagination.total,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                onChange: (page, pageSize) => {
                  setState(prev => ({
                    ...prev,
                    pagination: { ...prev.pagination, current: page, pageSize: pageSize || 20 }
                  }));
                  loadNotifications();
                }
              }}
            />
          )}
        </Spin>
      </Drawer>

      {/* 通知详情模态框 */}
      <Modal
        title="通知详情"
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setSelectedNotification(null);
        }}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {selectedNotification && (
          <div>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Title level={4}>{selectedNotification.title}</Title>
                <Space>
                  {getNotificationIcon(selectedNotification.type)}
                  <Tag color={getPriorityColor(selectedNotification.priority)}>
                    {selectedNotification.priority}
                  </Tag>
                  {selectedNotification.category && (
                    <Tag>{selectedNotification.category}</Tag>
                  )}
                </Space>
              </div>
              
              <Divider />
              
              <div>
                <Text>{selectedNotification.content}</Text>
              </div>
              
              {selectedNotification.actions && selectedNotification.actions.length > 0 && (
                <div>
                  <Divider />
                  <Space>
                    {selectedNotification.actions.map((action) => (
                      <Button
                        key={action.id}
                        type={action.style === 'primary' ? 'primary' : 'default'}
                        danger={action.style === 'danger'}
                        onClick={() => {
                          if (action.url) {
                            window.open(action.url, '_blank');
                          }
                        }}
                      >
                        {action.label}
                      </Button>
                    ))}
                  </Space>
                </div>
              )}
              
              <Divider />
              
              <div>
                <Space direction="vertical" size="small">
                  {selectedNotification.senderName && (
                    <Text type="secondary">发送者: {selectedNotification.senderName}</Text>
                  )}
                  <Text type="secondary">
                    创建时间: {new Date(selectedNotification.createdAt).toLocaleString()}
                  </Text>
                  {selectedNotification.sentAt && (
                    <Text type="secondary">
                      发送时间: {new Date(selectedNotification.sentAt).toLocaleString()}
                    </Text>
                  )}
                  {selectedNotification.readAt && (
                    <Text type="secondary">
                      阅读时间: {new Date(selectedNotification.readAt).toLocaleString()}
                    </Text>
                  )}
                </Space>
              </div>
            </Space>
          </div>
        )}
      </Modal>
    </>
  );
}

// 导出类型
export type { NotificationCenterProps };